package com.company.main;

import org.junit.Assert;
import org.junit.jupiter.api.Test;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * 示例 1:
 *
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 *
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * 说明:
 *
 * 所有输入只包含小写字母 a-z 。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String lastCommon = "";
        for (int i = 0; i <= strs[0].length(); i++) {
            String currentCommon = strs[0].substring(0, i);
            for (String str : strs) {
                if (! str.startsWith(currentCommon)) {
                    return lastCommon;
                }
            }
            lastCommon = currentCommon;
        }
        return lastCommon;
    }

    @Test
    public void test1() {
        String[] str = {"flower","flow","flight"};
        Assert.assertEquals("fl", longestCommonPrefix(str));
    }

    @Test
    public void test2() {
        String[] str = {"dog","racecar","car"};
        Assert.assertEquals("", longestCommonPrefix(str));
    }

    @Test
    public void test3() {
        String[] str = {"a"};
        Assert.assertEquals("a", longestCommonPrefix(str));
    }

    @Test
    public void test4() {
        String[] str = {};
        Assert.assertEquals("", longestCommonPrefix(str));
    }

    @Test
    public void test5() {
        String[] str = {"a", "a"};
        Assert.assertEquals("a", longestCommonPrefix(str));
    }
}
